#!/usr/bin/python
# coding=utf-8
   
"""android改包名
"""
__author__ ='nigg'
__email__ = '' 
VERSION = "v1.0"

import os, sys, re, time, getopt, string
import shutil
import glob

opts, args = getopt.getopt(sys.argv[1:], "hs:t:o:e:r:u:", ["help", "src=", "to=", "odir=", "ext=", "sregex=", "sto="])
#原包名
src_name = ""
#变后包名
to_name = ""
#目录
odir = ""
#需要替换的文件后缀
ext_name = ""
#匹配正则表达式
sregex = ""
#替换后的字符串
sto = ""

def usage():
    print ("Usage:change_pname.py [ops]")

if not opts:
    usage()
    sys.exit()
else:
    for op, value in opts:
#        print "op:value="+op+":"+value
        if op == "-s" or op == "--src":
            src_name = value
        elif op == "-t" or op == "--to":
            to_name = value
        elif op == "-o" or op == "--odir":
            odir = value
        elif op == "-r" or op == "--sregex":
            sregex = value 
        elif op == "-e" or op == "--ext":
            ext_name = value 
        elif op == "-u" or op == "--sto":
            sto = value        
        elif op == "-h" or op == "--help":
            usage()
            sys.exit()

text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
_null_trans = string.maketrans("", "")

def istextfile(filename, blocksize = 512):
    return istext(open(filename).read(blocksize))

def istext(s):
    if "\0" in s:
        return 0
    
    if not s:  # Empty files are considered text
        return 1

    # Get the non-text characters (maps a character to itself then
    # use the ‘remove’ option to get rid of the text characters.)
    t = s.translate(_null_trans, text_characters)

    # If more than 30% non-text characters, then
    # this is considered a binary file
    if len(t)/len(s) > 0.30:
        return 0
    return 1

def run_sub(filelist, strregexs, strtos):
    if filelist:
        ssrcs = [];
        for strregex in strregexs: 
            ssrcs.append(re.compile(strregex,re.DOTALL));          
        for filename in filelist:   
            fileread = open(filename,'r');   
            filer = fileread.read();
            sub = filer
            need_write = False
            i = 0;
            for ssrc in ssrcs:
                sto = strtos[i];
                m = re.search(ssrc, sub)  
                if m:
                    need_write = True
                    sub = re.sub(ssrc,sto,sub,0); #替换sregex 为 sto
                fileread.close();
                if m:
                    print strregexs[i];
                    print filename;
#                    print sub;
#                    break
                i = i + 1;
            if need_write:
                fileok = open(filename,'w');   
                fileok.write(sub);   
                fileok.close();   
#            if i:
#                break


def main():
    '''主函数'''
#    print "src_name="+src_name+",to_name="+to_name+",sregex="+sregex
    
    os.chdir(odir);   
    c1 = os.walk(os.getcwd());   
    filelist = [];
    for c2 in c1:   
        for c3 in c2[2]:
            c4 = os.path.join(c2[0],c3);   
            c5 = os.path.splitext(c4);
            if istextfile(c4):   
                if (ext_name == "*" or ext_name == "") or c5[1] == ext_name:   
                    filelist.append(c4);   
                else:   
                    pass;   
#    print filelist;
    
    items0 = src_name.split(".")
    items1 = to_name.split(".")
    strregexs = ["\.".join(items0), "/".join(items0), "_".join(items0), "-".join(items0)] 
    strtos = [".".join(items1), "/".join(items1), "_".join(items1), "-".join(items1)]
    run_sub(filelist, strregexs, strtos)
    
    src_dir = odir + "\\smali\\" + "\\".join(items0)
    to_dir = odir + "\\smali\\" + "\\".join(items1)
    if os.path.exists(src_dir):
        if os.path.exists(to_dir):
            shutil.rmtree(to_dir)        
        shutil.copytree(src_dir, to_dir)
        shutil.rmtree(src_dir)

if __name__ == "__main__":
  sys.exit(main())
